/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

-- DROP FUNCTION IF EXISTS fn_geo_distance;

CREATE OR REPLACE FUNCTION fn_geo_distance(
  lng1d double precision,
  lat1d double precision,
  lng2d double precision,
  lat2d double precision
) RETURNS double precision AS
$BODY$
DECLARE
  MPH_KM    double precision := 1.609344;
  lat1_rad  double precision := radians(lat1d);
  lat2_rad  double precision := radians(lat2d);
  theta     double precision := lng1d - lng2d;
  theta_rad double precision := radians(theta);
  dist      double precision;
BEGIN
  dist = sin(lat1_rad) * sin(lat2_rad) + cos(lat1_rad) * cos(lat2_rad) * cos(theta_rad);
  dist = acos(dist);
  dist = degrees(dist);
  dist = dist * 60 * 1.1515;
  dist = dist * MPH_KM;
  RETURN dist;
END;
$BODY$
  LANGUAGE plpgsql;
